import Flutter
import UIKit

import StoreKit
public class SwiftTupgradePlugin: NSObject, FlutterPlugin, SKStoreProductViewControllerDelegate {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "tupgrade", binaryMessenger: registrar.messenger())
    let instance = SwiftTupgradePlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
        case "getPlatformVersion":
            result("iOS " + UIDevice.current.systemVersion)
        case "toAppStore":
            justInstall(call, result: result)
        default:
            result (FlutterMethodNotImplemented)
    }
  }

  private func justInstall(_ call: FlutterMethodCall, result: @escaping FlutterResult) -> Void {
    let param: NSDictionary = call.arguments as! NSDictionary
    let installPath: String = param["path"] as! String
    let controller: FlutterViewController = UIApplication.shared.keyWindow?.rootViewController as! FlutterViewController
    DispatchQueue.main.async {
// Call the desired channel message here.
        if #available(iOS 10.3 , *) {
            if(!installPath.hasPrefix("http")) {
                let storeProductVC = SKStoreProductViewController.init()
                storeProductVC.delegate = self
                storeProductVC.loadProduct(withParameters: [SKStoreProductParameterITunesItemIdentifier: installPath]) { (ret: Bool, error: Error?) in
                    // if(error != nil) {
                    //     result(String("error"))
                    // } else {
                    //     result(String("positive"))
                    // }
                }
                controller.present(storeProductVC, animated: true) {
                }
                return
            }
        }
        if(!installPath.hasPrefix("http")) {
            UIApplication.shared.openURL(URL.init(string: "itms-apps://itunes.apple.com/app/id" + installPath)!)
        } else {
            UIApplication.shared.openURL(URL.init(string: installPath)!)
        }
    }
  }

  public func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
      viewController.dismiss(animated: true, completion: nil)
  }
}
